﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AdminStyem.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace AdminStyem.Repositories
{

    /// <summary>
    /// 接口
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public class BaseRespository<T> :IBaseRespository<T> where T : class
    {
        /// <summary>
        /// 上下文
        /// </summary>
        BaseDbContext db;

        public BaseRespository(BaseDbContext db)
        {
            this.db = db;
        }

        public async Task<int> add(T entity)
        {
            db.Set<T>().Add(entity);    
            return await db.SaveChangesAsync();
        }

        public async Task<int> AddRange(IEnumerable<T> entities)
        {
            db.Set<T>().AddRange(entities);
            return await db.SaveChangesAsync();
        }

        public async Task<int> delete(T entity)
        {
           db.Set<T>().Remove(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteRange(IEnumerable<int> Ids)
        {
            db.Set<T>().RemoveRange( db.Set<T>().Find(Ids));
            return await db.SaveChangesAsync();
        }

        public  async Task<List<T>> GetAll()
        {
            return  await db.Set<T>().ToListAsync();
          
        }

        public async Task<List<T>> GetAll(Expression<Func<T, bool>> expression)
        {
           return await db.Set<T>().Where(expression).ToListAsync();
        }

        public async Task<T> GetByid(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }

        public async Task<int> update(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdateRange(IEnumerable<T> Entities)
        {
            db.Set<T>().UpdateRange(Entities);
            return await db.SaveChangesAsync();
        }

        public IQueryable<T> Queryable()
        {
            return db.Set<T>().AsQueryable();
        }

        /// <summary>
        /// 根据条件查第一条
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual async Task<T> QueryFirstAsync(Expression<Func<T, bool>> predicate)
        {
            return await db.Set<T>().FirstOrDefaultAsync(predicate);
        }
    }
}
